import Axios from 'axios'
import {Message} from 'element-ui'
import Util from './index';
import {getToken, removeToken} from './token'

if (process.env.NODE_ENV === 'development') {
	Axios.defaults.baseURL = 'http://127.0.0.1:8081'
} else if (process.env === 'production') {
	Axios.defaults.baseURL = 'https://netease2.bluej.cn/';
}

Axios.defaults.timeout = 10000;
Axios.defaults.headers.post['Content-Type'] = 'application/x-www-form-urlencoded;charset=UTF-8';

Axios.interceptors.request.use(config => {
	let info = getToken();
	if (!Util.isNullOrBlank(info)) {
		info = JSON.parse(info);
		let header = {version: 1.0, source: 'Web', token: info.token, uid: info.uid};
		config.headers['X-Auth-Token'] = JSON.stringify(header)
	}
	return config
}, err => {
	Message.error({message: '请求错误!'});
	return Promise.reject(err)
});

Axios.interceptors.response.use(response => {
	const data = response.data;
	if (data.code === 0) {
		return data.result
	} else if (data.code === 403) {
		Message.error(data.message);
		removeToken();
		location.reload();// 为了重新实例化vue-router对象 避免bug
	} else {
		Message.error("未知错误!");
		return Promise.reject(null)
	}
}, error => {
	Message.error({message: '请求错误!'});
	return Promise.reject(error)
});

export function get(url, params) {
	return new Promise((resolve, reject) => {
		Axios.get(url, params).then(res => {
			resolve(res)
		}).catch(err => {
			reject(err)
		})
	})
}

export function post(url, params) {
	return new Promise((resolve, reject) => {
		Axios.post(url, params).then(res => {
			resolve(res);
		}).catch(err => {
			reject(err)
		})
	})
}